package transportManagement.servlet;

import java.io.IOException;
import java.security.InvalidParameterException;
import java.text.ParseException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import accountManagement.Employee;
import transportManagement.TransportBoard;
import transportManagement.Transport;
import common.Date;
	
/**
 * Servlet implementation class InsertLibro
 */
@WebServlet("/ServletCreateTransport")
public class ServletCreateTransport extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	/**
     * @see HttpServlet#HttpServlet()
     */
    public ServletCreateTransport() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doService(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doService(request, response);
	}

    private void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	try {
    		Object user = request.getSession().getAttribute("user");
        	if(user == null || !(user instanceof Employee)) {
        		throw new InvalidParameterException("Non disponi dei privilegi necessari per accedere alla pagina richiesta");
        	}
    		String transportId = request.getParameter("transportId");
    		String origin = request.getParameter("origin");
    		String destination = request.getParameter("destination");
    		
			Date departureDate = Date.parseDate(request.getParameter("departureDate"));
			Date arrivalDate = Date.parseDate(request.getParameter("arrivalDate"));
			double seatPrize = Double.parseDouble(request.getParameter("seatPrize"));
			
			Transport transport = new Transport(transportId, origin, destination, departureDate,
					arrivalDate,seatPrize);
			
			TransportBoard.getInstance().add(transport);
			
			request.setAttribute("resultTitle", "Inserimento corsa");
			request.setAttribute("resultContent", "Inserimento riuscita");
			request.getRequestDispatcher("/result.jsp").forward(request, response);
		} catch(InvalidParameterException | ParseException | NumberFormatException e) {
			request.setAttribute("error", e.getMessage());
			request.getRequestDispatcher("/errorPage.jsp").forward(request, response);
		}
    }
}

